<!-- 碳排放因子库-组织因子库 -->

<template>
  <div>
    <div class="m_contentBox">
      <a-card>
        <div class="m_aCardBox">
          <div class="tabBox">
            <a-tabs :activeKey="activeKey" @change="onChangeActiveKey">
              <a-tab-pane key="1" tab="碳排因子">
                <div class="tabInnerBox">
                  <div class="table-page-search-wrapper">
                    <a-form-model :model="queryParam" layout="inline" @keyup.enter.native="searchQuery">
                      <a-row :gutter="24">
                        <a-col :span="6">
                          <a-form-model-item label="因子名称">
                            <a-input v-model="queryParam.name" allowClear placeholder="请输入"></a-input>
                          </a-form-model-item>
                        </a-col>
                        <a-col :span="6">
                          <a-form-model-item label="因子分类">
                            <a-select v-model="queryParam.productClassification" allowClear placeholder="请选择" show-search
                                      :filter-option="filterOption">
                              <a-select-option :value="item.value" v-for="(item,index) in product_typeData" :key="item.value">
                                {{ item.text }}
                              </a-select-option>
                            </a-select>
                          </a-form-model-item>
                        </a-col>
                        <a-col :span="6">
                          <a-form-model-item label="适用场景">
                            <a-input v-model="queryParam.scene" allowClear placeholder="请输入"></a-input>
                          </a-form-model-item>
                        </a-col>
                        <a-col :span="6">
                          <a-form-model-item label="适用行业">
                            <a-select v-model="queryParam.industryId" allowClear placeholder="请选择"
                                      show-search :filter-option="filterOption">
                              <a-select-option :value="item.id" v-for="(item,index) in industryData" :key="index">
                                {{ item.name }}
                              </a-select-option>
                            </a-select>
                          </a-form-model-item>
                        </a-col>
                        <a-col :span="6">
                          <a-form-model-item label="发布机构">
                            <a-input v-model="queryParam.releaseOrg" allowClear placeholder="请输入"></a-input>
                          </a-form-model-item>
                        </a-col>
                        <a-col :span="6">
                          <a-form-model-item label="适用地区">
                            <a-input v-model="queryParam.ownership" allowClear placeholder="请输入"></a-input>
                          </a-form-model-item>
                        </a-col>
                        <a-col :span="6">
                          <a-form-model-item label="排放系数种类">
                            <a-select v-model="queryParam.category" allowClear placeholder="请选择" show-search
                                      :filter-option="filterOption">
                              <a-select-option :value="item.value" v-for="(item,index) in emission_factor_category" :key="item.value">
                                {{ item.text }}
                              </a-select-option>
                            </a-select>
                          </a-form-model-item>
                        </a-col>
                        <a-col :span="6">
                          <a-form-model-item label="碳排因子数据库">
                            <a-select v-model="queryParam.emissionFactorDatabase" allowClear placeholder="请选择" show-search
                                      :filter-option="filterOption">
                              <a-select-option :value="item.value" v-for="(item,index) in emission_factor_database" :key="item.value">
                                {{ item.text }}
                              </a-select-option>
                            </a-select>
                          </a-form-model-item>
                        </a-col>
                        <a-col :span="6">
                          <a-form-model-item label="">
                            <a-button type="primary" @click="searchQuery">查询</a-button>
                            <a-button style="margin-left: 8px" @click="searchReset">重置</a-button>
                          </a-form-model-item>
                        </a-col>
                      </a-row>
                    </a-form-model>
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
          <!-- 组织因子 -->
          <div class="cardBox" v-if="activeKey == 1">
            <div class="addBtn m_hoverCP" @click="onAdd">
              <img class="addBtn_icon " src="@assets/img/img27.png" alt=""/>新增因子
            </div>
            <div class="m_mt24" v-if="addListData && addListData.length > 0">
              <a-table ref="table" :columns="columns" :dataSource="addListData" :loading="loading"
                       :pagination="ipagination" :scroll="{ x: true }" :bordered="false" class="" rowKey="id"
                       size="middle" @change="handleTableChange">
                <div slot="factorValue" slot-scope="text, record">{{ (Number(record.factorValue)).toFixed(4) }}</div>
                <div slot="Unit" slot-scope="text, record">{{ record.numeratorUnit }}/{{ record.denominatorUnit }}</div>
                <template slot="state" slot-scope="text, record">
                  <div class="stateBox stateBox1" v-if="text == 1"> 已发布</div>
                  <div class="stateBox stateBox2" v-if="text == 0"> 未发布</div>
                </template>
                <div style="width:280px"  slot="action" slot-scope="text, record">
                  <a @click="onDetail(record)">详情</a>
                  <a-divider type="vertical" />
                  <a @click="onChangeStatus(record)" v-if="record.state == 1">取消发布</a>
                  <a @click="onChangeStatus(record)" v-if="record.state == 0">发布</a>
                  <a-divider type="vertical" />
                  <a-popconfirm title="确定删除吗?" cancelText="取消" okText="确定" @confirm="() => onDelete(record)">
                    <a>删除</a>
                  </a-popconfirm>
                  <a-divider type="vertical" />
                  <a @click="onCopy(record,1)">编辑</a>
                  <a-divider type="vertical" />
                  <a @click="onCopy(record,2)">复制</a>

                </div>
              </a-table>
            </div>
            <emptyBox text1="暂无搜索结果" @change="onAdd" v-else></emptyBox>
          </div>
        </div>
      </a-card>
    </div>
    <!-- 详情弹窗 -->
    <section class="m_popupBox" v-if="isShowDetailPopup">
      <tpyzDetail ref="tpyzDetail" @back="back"></tpyzDetail>
    </section>
    <!-- 表单弹窗 -->
    <section class="m_popupBox" v-if="isShowFormPopup">
      <tpyzForm ref="tpyzForm" @back="back" :editFlag="editFlag"></tpyzForm>
    </section>
  </div>
</template>

<script>
import Vue from "vue";
import {ACCESS_TOKEN} from "@/store/mutation-types";
import {cloneObject} from "@/utils/util";
import {deleteAction, getAction, postAction} from '@/api/manage'
import emptyBox from '@comp/common/emptyBox.vue'
import tpyzDetail from '@views/module_managePlatform/emissionFactor/modules/tpyzDetail.vue'
import tpyzForm from '@views/module_managePlatform/emissionFactor/modules/tpyzForm.vue'

import {INDUSTRY} from "@/common/constKey";

export default {
  name: 'zzyzkView',
  components: {
    emptyBox,
    tpyzDetail,
    tpyzForm,
  },
  data() {
    return {
      activeKey: '1', // 1我的添加 2我的收藏
      // ======================================================
      loading: false,
      queryParam: {
        type: 1, // 类型（1=碳排因子库，2=组织因子库）
        token: Vue.ls.get(ACCESS_TOKEN),
      },
      columns: [{
        title: '碳排因子数据库',
        align: 'center',
        dataIndex: 'emissionFactorDatabase_dictText',
      },
        {
        title: '因子名称',
        align: 'center',
        dataIndex: 'name',
      }, {
        title: '因子值',
        align: 'center',
        dataIndex: 'factorValue',
        scopedSlots: {customRender: 'factorValue'},
      }, {
        title: '单位',
        align: 'center',
        scopedSlots: {customRender: 'Unit'},
      }, {
        title: '状态',
        align: 'center',
        dataIndex: 'state',
        width: 70,
        scopedSlots: {customRender: 'state'},
      }, {
        title: '因子分类',
        align: 'center',
        dataIndex: 'productClassification_dictText',
      }, {
        title: '适用场景',
        align: 'center',
        dataIndex: 'scene',
      }, {
        title: '适用行业',
        align: 'center',
        dataIndex: 'industry',
      }, {
        title: '发布机构',
        align: 'center',
        dataIndex: 'releaseOrg',
      }, {
        title: '发布年份',
        align: 'center',
        dataIndex: 'releaseYear',
        sorter: (a, b) => a.releaseYear - b.releaseYear,
      },{
        title: '适用地区',
        align: 'center',
        dataIndex: 'ownership',
      },{
        title: '排放系数种类',
        align: 'center',
        dataIndex: 'category_dictText',
      },{
        title: '操作',
        dataIndex: 'action',
        align: 'center',
        fixed: 'right',
        width: 200,
        scopedSlots: {customRender: 'action'},
      }],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条';
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      // ======================================================
      addListData: [], // 我的添加数据
      collectListData: [], // 我的收藏数据
      isShowDetailPopup: false, // 详情弹窗
      isShowFormPopup: false, // 表单弹窗
      fmData: [], // 分母选项数据
      industryData: [], // 行业数据
      getCreatePeopleData: [], // 创建人数据
      product_typeData:[], //因子分类
      emission_factor_category:[], //排放系数种类
      emission_factor_database:[], //排放数据库
      editFlag: null
    };
  },
  created() {
    this.init()
    this.getData()
  },
  methods: {
    /**
     * 下拉框数据过滤
     */
    filterOption(input, option) {
      return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    /**
     * 复制组织因子库
     */
    onCopy(item,flag) {

      this.editFlag = flag
      console.log('onCopy', item)
      getAction('/emission/factor/cyEmissionFactor/listInfo', {
        id: item.id
      }).then((res) => {
        if (res.success) {
          let resData = res.result || {}
          console.log('resData', resData)

          let formData = null;

          resData.gasList = resData.gasList || []
          resData.gasList.forEach(gasItem =>{
            delete gasItem.id
          })

          if(flag == 1){
            formData = {
            id: resData.emissionFactorObject.id,  //因子id
            organizationId: resData.emissionFactorObject.organizationId, // 组织id
            deptId: resData.emissionFactorObject.deptId,  // 部门id
            name: resData.emissionFactorObject.name, // 因子名称
            type: resData.emissionFactorObject.type, // 数据库
            model: resData.emissionFactorObject.model, // 规格型号
            industryId: resData.emissionFactorObject.industryId, // 适用行业
            industry: resData.emissionFactorObject.industry, // 适用行业
            productClassification: resData.emissionFactorObject.productClassification, // 因子分类
            scene: resData.emissionFactorObject.scene, // 适用场景
            instruction: resData.emissionFactorObject.instruction, // 因子说明
            numeratorUnit: resData.emissionFactorDataObject.numeratorUnit, // 分子
            numeratorUnitId: resData.emissionFactorDataObject.numeratorUnitId, // 分子
            denominatorUnit: resData.emissionFactorDataObject.denominatorUnit, // 分母
            denominatorUnitId: resData.emissionFactorDataObject.denominatorUnitId, // 分母
            factorValue: resData.emissionFactorDataObject.factorValue, // 因子值
            computerType: resData.emissionFactorDataObject.type, // 手动|配比
            releaseOrg: resData.emissionFactorObject.releaseOrg, // 发布机构
            releaseYear: resData.emissionFactorObject.releaseYear, // 发布年份
            sourceType: resData.emissionFactorObject.sourceType, // 来源类型
            docType: resData.emissionFactorObject.docType, // 文献类型
            ownership: resData.emissionFactorObject.ownership, // 适用地区
            sourceFile: resData.emissionFactorObject.sourceFile, // 来源文件
            sourceUrlLink: resData.emissionFactorObject.sourceUrlLink, // 来源网址链接
            attachments: resData.emissionFactorObject.attachments, // 附件
            emissionFactorDatabase: resData.emissionFactorObject.emissionFactorDatabase, // 碳排因子数据库
            gwpVersion: resData.emissionFactorObject.gwpVersion, // gwp版本
            category: resData.emissionFactorObject.category, // 排放系数种类
            gasList: resData.gasList,
          }
        }else{
            formData = {
            name: resData.emissionFactorObject.name, // 因子名称
            type: resData.emissionFactorObject.type, // 数据库
            model: resData.emissionFactorObject.model, // 规格型号
            industryId: resData.emissionFactorObject.industryId, // 适用行业
            industry: resData.emissionFactorObject.industry, // 适用行业
            productClassification: resData.emissionFactorObject.productClassification, // 因子分类
            scene: resData.emissionFactorObject.scene, // 适用场景
            instruction: resData.emissionFactorObject.instruction, // 因子说明
            numeratorUnit: resData.emissionFactorDataObject.numeratorUnit, // 分子
            numeratorUnitId: resData.emissionFactorDataObject.numeratorUnitId, // 分子
            denominatorUnit: resData.emissionFactorDataObject.denominatorUnit, // 分母
            denominatorUnitId: resData.emissionFactorDataObject.denominatorUnitId, // 分母
            factorValue: resData.emissionFactorDataObject.factorValue, // 因子值
            computerType: resData.emissionFactorDataObject.type, // 手动|配比
            releaseOrg: resData.emissionFactorObject.releaseOrg, // 发布机构
            releaseYear: resData.emissionFactorObject.releaseYear, // 发布年份
            sourceType: resData.emissionFactorObject.sourceType, // 来源类型
            docType: resData.emissionFactorObject.docType, // 文献类型
            ownership: resData.emissionFactorObject.ownership, // 适用地区
            sourceFile: resData.emissionFactorObject.sourceFile, // 来源文件
            sourceUrlLink: resData.emissionFactorObject.sourceUrlLink, // 来源网址链接
            attachments: resData.emissionFactorObject.attachments, // 附件
            gasList: resData.gasList,
          }
      }
          this.isShowFormPopup = true
          this.$nextTick(() => {
            console.log('tpyzForm', this.$refs)
            this.$refs.tpyzForm.queryParam = formData
            if (formData.computerType == 2) {
              console.log('tpyzForm computerType2')
              // 分子
              getAction('/CyFactorUnit/cyFactorUnit/list').then((resA) => {
                if (resA.success) {
                  let fzData = resA.result.records || []
                  let theIndex = fzData.findIndex(ele => ele.id == formData.numeratorUnitId)
                  if (theIndex > -1) {
                    getAction('/gas/cyGasStore/listGasName', {
                      factorRealUnit: fzData[theIndex].factorRealUnit
                    }).then((resB) => {
                      if (resB.success) {
                        console.log('tpyzForm computerType2', resB)
                        this.$refs.tpyzForm.gasData = resB.result || []
                        this.$refs.tpyzForm.computeFactorValue()
                      }
                    });
                  }
                }
              });
            }
          })
        }
      })
    },
    /**
     * 停用/启用组织因子库
     */
    onChangeStatus(item) {
      let theItem = cloneObject(item)
      if (theItem.state == 1) {
        theItem.state = 0
      } else if (theItem.state == 0) {
        theItem.state = 1
      }
      getAction('/emission/factor/cyEmissionFactor/changeStatus', theItem).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.getData()
        }
      });
    },
    /**
     * 删除组织因子库
     */
    onDelete(item) {
      deleteAction('/emission/factor/cyEmissionFactor/delete', {id: item.id}).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.getData()
        }
      });
    },
    /**
     * 取消收藏碳排因子库
     */
    onDelCollect(item) {
      deleteAction('/CyEmissionFactorCollect/cyEmissionFactorCollect/delete', {id: item.id}).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.getData()
        }
      });
    },
    /**
     * 详情
     */
    onDetail(item, ShouCang) {
      this.isShowDetailPopup = true
      this.$nextTick(() => {
        console.log('onDetail', this.$refs)
        this.$refs.tpyzDetail.detailIndex = 0
        this.$refs.tpyzDetail.detailKeys = [item.id]
        this.$refs.tpyzDetail.getData(ShouCang)
      })
    },
    /**
     * 查询
     */
    searchQuery() {
      console.log('searchQuery');
      this.ipagination.current = 1
      this.getData()
    },
    /**
     * 重置
     */
    searchReset() {
      console.log('searchReset');
      if (this.activeKey == 1) {
        // 组织因子
        this.queryParam = {
          type: 1, // 类型（1=碳排因子库，2=组织因子库）
          token: Vue.ls.get(ACCESS_TOKEN),
        }
      }
      this.ipagination.current = 1
      this.getData()
    },
    back() {
      this.isShowDetailPopup = false
      this.isShowFormPopup = false
      this.getData()
    },
    /**
     * 新增因子
     */
    onAdd() {
      console.log('onAdd');
      this.isShowFormPopup = true
    },
    handleTableChange(pagination, filters, sorter) {
      console.log(pagination);
      this.ipagination = pagination;
      this.getData();
    },
    /**
     * 切换tab
     * @param key 1我的添加 2我的收藏
     */
    onChangeActiveKey(key) {
      console.log('onChangeActiveKey', key);
      this.activeKey = key
      this.getData()
    },
    getData() {
      if (this.activeKey == 1) {
        // 组织因子
        let reqData = cloneObject(this.queryParam)
        reqData.pageNo = this.ipagination.current
        reqData.pageSize = this.ipagination.pageSize
        getAction('/emission/factor/cyEmissionFactor/emissionList', reqData).then((res) => {
          if (res.success) {
            this.addListData = res.result.records || []
            this.ipagination.total = res.result.total
          }
        });
      }
    },
    init(){
      // 创建人
      getAction('/emission/factor/cyEmissionFactor/getCreatePeople', {
        pid: INDUSTRY
      }).then((res) => {
        if (res.success) {
          this.getCreatePeopleData = res.result || []
        }
      });
      // 行业
      getAction('/sys/category/childList', {
        pid: INDUSTRY
      }).then((res) => {
        if (res.success) {
          this.industryData = res.result || []
        }
      });
      // 分母单位
      getAction('/emission/factor/cyEmissionUnit/getAllUnit').then((res) => {
        if (res.success) {
          this.fmData = res.result || []
        }
      });
      // 因子分类
      getAction('/sys/api/getDictItems', {
        dictCode: 'product_type'
      }).then((res) => {
        this.product_typeData = res || []
        console.log('getDictItems product_type =>', res)
      });
      //排放洗漱种类
      getAction('/sys/api/getDictItems', {
        dictCode: 'emission_factor_category'
      }).then((res) => {
        this.emission_factor_category = res || []
        console.log('getDictItems document_type =>', res)
      });
      //碳排因子数据库
      getAction('/sys/api/getDictItems', {
        dictCode: 'emission_factor_database'
      }).then((res) => {
        this.emission_factor_database = res || []
        console.log('getDictItems document_type =>', res)
      });
    }
  },
};

</script>

<style lang="less" scoped>
/deep/ .ant-card-body {
  background: #F5F8F7;
}

.tabBox {
  background: #FFFFFF;
  border-radius: 3px;
}

.tabInnerBox {
  padding: 8px 24px 0;
}

.cardBox {
  margin-top: 24px;
  padding: 24px;
  background: #FFFFFF;
  border-radius: 3px;
}

.addBtn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 112px;
  height: 32px;
  background: #148958;
  border-radius: 3px;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);

  .addBtn_icon {
    width: 16px;
    height: 16px;
  }
}

.stateBox {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 66px;
  height: 32px;
  border-radius: 3px;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
}

.stateBox1 {
  background: #E3F9E9;
  border: 1px solid #2BA471;
  color: #2BA471;
}

.stateBox2 {
  background: #FFF0ED;
  border: 1px solid #D54941;
  color: #D54941;
}
</style>
